package com.rcp.manager;/* Restaurant Control Program >> Restaurant Manager */

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;


@WebServlet("/StaffManagerServlet")
public class StaffManagerServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	Connection connection = Nexus.connection;
	Schedule schedule;
	Employee employee;
	
    public StaffManagerServlet() {
        super();
    }


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		System.out.println(1);
		
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		System.out.println(2);
		//Check if connection is active
		if(this.connection == null){
			establishConnection();
		} else
			try {
				if(this.connection.isClosed()){
					establishConnection();
				}
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		System.out.println(3);
		//Get employee ID
		int employeeID = Integer.parseInt(request.getParameter("selected"));
		System.out.println( 4 + "  EMPLOYEE ID: " + employeeID);
		//Get First/Last name & status
		String firstname = "";
		String lastname = "";
		int statusInt = 0;
		String status = "";
		
		try {
			String preparedQuery = 
					"SELECT FirstName, LastName, status FROM Employees WHERE EmployeeID = ?;";
			
			PreparedStatement ps = (PreparedStatement) connection.prepareStatement(preparedQuery);
			ps.setInt(1, employeeID);
			
			ResultSet results = ps.executeQuery();
			results.first();								//VERY important
			
			firstname = results.getString("firstname");
			lastname = results.getString("lastname");
			statusInt = results.getInt("status");
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		System.out.println(5);
		//Set Status
		if(statusInt == 0){
			status = "Waiter";
		}
		else if(statusInt == 1){
			status = "Host";
		}
		else if(statusInt == 2){
			status = "Manager";
		}
		
		//Get Schedule
		try {
			String preparedQuery = 
					"SELECT Schedule FROM Schedule WHERE EmployeeID = ?;";
			
			PreparedStatement ps = (PreparedStatement) connection.prepareStatement(preparedQuery);
			ps.setInt(1, employeeID);
			
			ResultSet results = ps.executeQuery();
			results.first();								//VERY important
			
			//Reading Object from BLOB
			//http://hans.liss.pp.se/node/700
			InputStream is = results.getBlob("schedule").getBinaryStream();
			ObjectInputStream ois = new ObjectInputStream(is);
			Object o = null;
			
			try {
				o = ois.readObject();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			} 
			
			this.schedule = (Schedule) o;

		} catch (SQLException e) {
			e.printStackTrace();
		}

		System.out.println(6);
		
		out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">");

		out.println("<html>");

		out.println("<head>");

		out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1\">");

		out.println("<title>Staff</title>");

		out.println("<link href=\"resources/CSS/Selected.css\" rel=\"stylesheet\" type=\"text/css\"/>");

		out.println("</head>");

		out.println("<script type='text/javascript'>");

		out.println("function toggle_visibility(id) {");

		out.println("var e = document.getElementById(id);");

		out.println("if(e.style.display == 'block')");

		out.println("e.style.display = 'none';");

		out.println("else");

		out.println("e.style.display = 'block';");

		out.println("}");

		out.println("</script>");

		out.println("<body>");

		out.println("<div class='center'>");

		out.println("<h1>" + firstname + " " + lastname + "</h1>");

		out.println("<br />");

		out.println("<table class='status'>");

		out.println("<tr>");

		out.println("<td>");

		out.println("Status: <b>" + status + "</b>");

		out.println("</td>");

		out.println("<td>");

		out.println("<button type='button' onClick=\"toggle_visibility('change')\">Change Status</button>");

		out.println("</td>");

		out.println("</tr>");

		out.println("</table>");

		out.println("<br />");

		out.println("<div id='change' style='display:none'>");
		
		out.println("<form name='input' action='StaffManagerServlet' method='post'>");
		
		out.println("<input type='hidden' name='employeeID' value='" + employeeID + "'></input>");

		out.println("<table class='status'>");

		out.println("<tr>");

		out.println("<td>");

		out.println("Change Status:");

		out.println("</td>");

		out.println("<td>");

		out.println("<select name='status' class='glass'>");

		out.println("<option value=''></option>");

		out.println("<option value='0'>Waiter</option>");

		out.println("<option value='1'>Host</option>");

		out.println("<option value='2'>Manager</option>");

		out.println("</select>");

		out.println("</td>");

		out.println("</tr>");

		out.println("</table>");

		out.println("</div>");

		out.println("<br />");

		out.println("<br />");
		
		out.println("<form name='erase' action='StaffManagerServlet' method='post'>");
		
		out.println("<table class='del'>");
		
		out.println("<tr>");
		
		out.println("<td>");

		out.println("<h2>Schedule</h2>");
		
		out.println("</td>");
		
		out.println("<td>");
		
		out.println("<button class='glass' name='delete' type='submit' value='" +  employeeID +"'>Delete</button>");
		
		out.println("</td>");
		
		out.println("</table>");
		
		out.println("</form>");


		out.println("<hr>");
		
		out.println("<br />");
		
		//Print Schedule
	
		out.println("<table class='schedule'>");
		
		LinkedHashMap<Integer, String> week = (LinkedHashMap<Integer, String>) request.getSession().getAttribute("week");
		LinkedHashMap<String, LinkedHashMap<String, String>> days = this.schedule.getDays();
			
		for(int i = 0; i < week.size(); i++){
			
			String day = week.get(i + 1);
			LinkedHashMap<String, String> today = days.get(day);
			Set<String> keys= today.keySet();
			Object[] time_in = keys.toArray();
	
			out.println("<tr>");
	
			out.println("<td class='days'>");
	
			out.println(day);
	
			out.println("</td>");
			
			for(int j = 0; j < time_in.length; j++){
				out.println("<td>");
				
				out.println("Clock In: ");
		
				out.println(" " + time_in[j] + " ");
				
				out.println("</td>");
				
				out.println("<td>");
	
				out.println("Clock Out: ");
		
				out.println(" " + today.get(time_in[j]) + " ");
				
				out.println("</td>");
			}
		
			out.println("</tr>");
			
		}
	
		out.println("</table>");
	
		out.println("<br />");
	
		//////
		
		out.println("<button type='button' class='glass' onClick=\"toggle_visibility('toggle')\">Modify Schedule</button>");
		
		out.println("<br />");
		
		out.println("<form name='modify' action='StaffManagerServlet' method='post'>");
		
		out.println("<input type='hidden' name='employeeID' value='" + employeeID + "'></input>");
		
		out.println("<input type='hidden' name='status' value='" + statusInt + "'></input>");

		
		out.println("<table class='schedule' id='toggle' style='display:none'>");

		//Modify Schedule
		for(int i = 0; i < week.size(); i++){

			String day = week.get(i + 1);
		
			out.println("<tr>");
	
			out.println("<td class='days'>");
	
			out.println(day);
	
			out.println("</td>");
	
			out.println("<td>");
	
			out.println("Clock In:");
	
			out.println("<input type=\"text\" class=\"time\" name=\"clock_in_hr\" maxlength=\"2\" size=\"2\" onkeyup=\"this.value=this.value.replace(/[^\\d]/,'')\" value=''/>");
	
			out.println(":");
	
			out.println("<input type=\"text\" class=\"time\" name=\"clock_in_min\" maxlength=\"2\" size=\"2\" onkeyup=\"this.value=this.value.replace(/[^\\d]/,'')\" value=''/>");
	
			out.println("<select name='in_time'>");
			
			out.println("<option value =''></option>");
	
			out.println("<option value=\"am\">AM</option>");
	
			out.println("<option value=\"pm\">PM</option>");
	
			out.println("</select>");
	
			out.println("</td>");
	
			out.println("<td>");
	
			out.println("Clock Out:");
	
			out.println("<input type=\"text\" class=\"time\" name=\"clock_out_hr\" maxlength=\"2\"  size=\"2\" onkeyup=\"this.value=this.value.replace(/[^\\d]/,'')\" value=''/>");
	
			out.println(":");
	
			out.println("<input type=\"text\" class=\"time\" name=\"clock_out_min\" maxlength=\"2\" size=\"2\" onkeyup=\"this.value=this.value.replace(/[^\\d]/,'')\" value=''/>");
	
			out.println("<select name='out_time'>");
			
			out.println("<option value =''></option>");
	
			out.println("<option value=\"am\">AM</option>");
	
			out.println("<option value=\"pm\">PM</option>");
	
			out.println("</select>");
	
			out.println("</td>");
	
			out.println("</tr>");
		
		}
		

		out.println("</table>");
		
		out.println("<br />");
		
		out.println("<button type='submit' action='StaffManagerServlet' class='glass'>Submit</button>");
	
		out.println("</form>");

		out.println("<br />");
		out.println("<br />");
		out.println("<br />");

		out.println("<div class='bottom'>");
		
		ArrayList<Double> costs = new ArrayList<Double>();
		
		//Get totals
		try {
			String preparedQuery = 
					"SELECT Cost FROM Orders WHERE EmployeeID = ?;";
			
			PreparedStatement ps = (PreparedStatement) connection.prepareStatement(preparedQuery);
			ps.setInt(1, employeeID);
			
			ResultSet results = ps.executeQuery();
			results.first();								//VERY important
			
			while(results.next()){
				costs.add(results.getDouble("cost"));
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		Double sum = 0.0;
		
		for(int i = 0; i < costs.size(); i ++){
			sum += costs.get(i);
		}
		
		out.println("<strong>Total receipts count: $" + sum + "</strong>");
		
		out.println("</div>");

		out.println("</div>");

		out.println("</body>");

		out.println("</html>");

		out.close();
	
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		
		int employeeID = Integer.parseInt(request.getParameter("employeeID"));
		
		if(request.getParameter("delete") != null){
			try {
				String preparedQuery = 
						"DELETE FROM Employees WHERE EmployeeID = ?;";
				
				PreparedStatement ps = (PreparedStatement) connection.prepareStatement(preparedQuery);
				ps.setInt(1, employeeID);
				
				ps.executeUpdate();
				
				response.sendRedirect("EmployeesTable");
				
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		else{
			
			this.schedule = new Schedule();
			
			//Fill out schedule
			
			LinkedHashMap<Integer, String> week = (LinkedHashMap<Integer, String>) request.getSession().getAttribute("week");
			
			String[] clock_in_hr = request.getParameterValues("clock_in_hr");
			String[] clock_in_min = request.getParameterValues("clock_in_min");
			String[] in_time = request.getParameterValues("in_time");
			String[] clock_out_hr = request.getParameterValues("clock_out_hr");
			String[] clock_out_min = request.getParameterValues("clock_out_min");
			String[] out_time = request.getParameterValues("out_time");
			
			//Sanity Check All Fields
			for(int i = 0; i < week.size(); i++){
				if( in_time[i].length() == 0 ){
					clock_in_hr[i] = "-";
					clock_in_min[i] = "-";
					in_time[i] = "-";
					clock_out_hr[i] = "-";
					clock_out_min[i] = "-";
					out_time[i] = "-";
				}
			}
			
			//Fill out schedule
			for(int i = 0; i < week.size(); i++){
				String day = week.get(i + 1);
				String in = clock_in_hr[i] + ":" + clock_in_min[i] + " " + in_time[i];
				String outT = clock_out_hr[i] + ":" + clock_out_min[i] + " " + out_time[i];
				
				this.schedule.addDay(day, in, outT);
				this.schedule.setEmployeeID(employeeID);
			}
			
			//Add to employee
			//this.employee.setSchedule(this.schedule);
			
			
			//Update Schedule to database
			try {
				String preparedQuery = 
						"UPDATE IGNORE Schedule SET Schedule = ? WHERE EmployeeID = ?;";
				
				PreparedStatement ps = (PreparedStatement) connection.prepareStatement(preparedQuery);
				ps.setObject(1, this.schedule);
				ps.setInt(2, employeeID);
				
				ps.executeUpdate();
				
			} catch (SQLException e) {
				e.printStackTrace();
			}
			
			//Update Status
			if(request.getParameter("status") != ""){
				try {
					String preparedQuery = 
							"UPDATE IGNORE Employees SET status = ? WHERE EmployeeID = ?;";
					
					PreparedStatement ps = (PreparedStatement) connection.prepareStatement(preparedQuery);
					ps.setInt(1, Integer.parseInt(request.getParameter("status")));
					ps.setInt(2, employeeID);
					
					ps.executeUpdate();
					
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			
			response.sendRedirect("EmployeesTable");
			
		}
		
	}
	
	
	public void establishConnection(){
		
		String dbURL = "jdbc:mysql://cs3.calstatela.edu:3306/cs437group01";
		String dbName = "";
		String username = "cs437group01";
		String password = "VHj#dj!v";
		String driver = "com.mysql.jdbc.Driver";
		 
		/*
		String dbURL = "jdbc:mysql://localhost:3306/";
		String dbName = "rcp";
		String username = "root";
		String password = "sesame";
		String driver = "com.mysql.jdbc.Driver";
		*/
		
		try {
			Class.forName(driver).newInstance();
			Nexus.connection = (Connection) DriverManager.getConnection(dbURL + dbName, username, password);
			this.connection = Nexus.connection;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void destroy(){
		try {
			connection.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		super.destroy();
	}

}
